package xyz.jiang.auth.controller;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import xyz.jiang.common.grace.result.GraceJSONResult;
import xyz.jiang.common.pojo.dto.RegistLoginDTO;
import xyz.jiang.common.pojo.entity.Users;
import xyz.jiang.common.pojo.vo.UsersVO;
import xyz.jiang.common.service.IUsersService;
import xyz.jiang.common.task.SMSTask;
import xyz.jiang.common.utils.IPUtil;
import xyz.jiang.common.utils.RedisUtils;
import xyz.jiang.common.utils.TokenUtils;

import java.util.concurrent.TimeUnit;

import static xyz.jiang.common.constants.RedisConstants.MOBILE_SMSCODE;
import static xyz.jiang.common.constants.TokenConstants.TOKEN_EXPIRE_TIME;
import static xyz.jiang.common.constants.TokenConstants.TOKEN_PREFIX;
import static xyz.jiang.common.grace.result.ResponseStatusEnum.*;

@RestController
@RequestMapping("/passport")
public class PassportController {

    @Autowired
    private SMSTask smsTask;

    @Autowired
    private IUsersService usersService;


    @GetMapping("/getSMSCode")
    public GraceJSONResult getSMSCode(String mobile, HttpServletRequest request) {

        if (StrUtil.isBlank(mobile)) {
            return GraceJSONResult.error();
        }
        String ip = IPUtil.getRequestIp(request);
        if (StrUtil.isBlank(ip)) {
            return GraceJSONResult.error();
        }

        // 判断是否已经发送过验证码，防止用户重复发送验证码，基于手机号判断
        RedisUtils.exists(MOBILE_SMSCODE + ":" + mobile);
        if (RedisUtils.exists(MOBILE_SMSCODE + ":" + mobile)) {
            return GraceJSONResult.errorCustom(SMS_NEED_WAIT_ERROR);
        }
        // 判断是否已经发送过验证码，防止用户重复发送验证码，基于ip判断
        if (RedisUtils.exists(MOBILE_SMSCODE + ":" + ip)) {
            return GraceJSONResult.errorCustom(SMS_NEED_WAIT_ERROR);
        }

        // 生成验证码
        String code = (int)((Math.random() * 9 + 1) * 100000) + "";

        // 发送验证码
        //smsTask.sendMsg(mobile, code);
        System.out.println(mobile + " 验证码为：" + code);

        // 验证码存入redis
        RedisUtils.setEx(MOBILE_SMSCODE + ":" + mobile, code, 1, TimeUnit.MINUTES);
        RedisUtils.setEx(MOBILE_SMSCODE + ":" + ip, code, 1, TimeUnit.MINUTES);


        return GraceJSONResult.ok();

    }


    @PostMapping("/register")
    public GraceJSONResult register(@Valid @RequestBody RegistLoginDTO registLoginDTO, HttpServletRequest request) {

        String mobile = registLoginDTO.getMobile();
        String code = registLoginDTO.getCode();

        if (StrUtil.isBlank(mobile) || StrUtil.isBlank(code)) {
            return GraceJSONResult.error();
        }
        // 判断验证码是否正确
        String redisCode = (String) RedisUtils.get(MOBILE_SMSCODE + ":" + mobile);
        if (StrUtil.isBlank(redisCode) || !redisCode.equalsIgnoreCase(code)) {
            return GraceJSONResult.errorCustom(SMS_CODE_ERROR);
        }

        Users user = usersService.queryMobileIfExist(mobile);
        if (!ObjectUtils.isEmpty(user)) {
            return GraceJSONResult.errorCustom(USER_ALREADY_EXIST_ERROR);
        }
        user = usersService.createUsers(mobile);

        // 删除redis验证码
        RedisUtils.delete(MOBILE_SMSCODE + ":" + mobile);

        return GraceJSONResult.ok(user);
    }

    @PostMapping("/login")
    public GraceJSONResult login(@Valid @RequestBody RegistLoginDTO loginDTO, HttpServletRequest request) {
        String mobile = loginDTO.getMobile();
        String code = loginDTO.getCode();

        String redisCode = (String)RedisUtils.get(MOBILE_SMSCODE + ":" + mobile);
        if (StrUtil.isBlank(redisCode) || !redisCode.equalsIgnoreCase(code)) {
            return GraceJSONResult.errorCustom(SMS_CODE_ERROR);
        }

        Users user = usersService.queryMobileIfExist(mobile);
        if (ObjectUtils.isEmpty(user)) {
            return GraceJSONResult.errorCustom(USER_ISNOT_EXIST_ERROR);
        }
        // 生成用户token
        String token = TokenUtils.crateToken(user.getId());
        System.out.println("token: " + token);
        RedisUtils.setEx(TOKEN_PREFIX + token,user.getId(),TOKEN_EXPIRE_TIME,TimeUnit.SECONDS);
        UsersVO usersVO = new UsersVO();
        BeanUtils.copyProperties(user,usersVO);

        usersVO.setToken(token);

        return GraceJSONResult.ok(usersVO);

    }

    @GetMapping("/logout")
    public GraceJSONResult logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            return GraceJSONResult.error();
        }
        RedisUtils.delete(TOKEN_PREFIX + token);
        return GraceJSONResult.ok();
    }
}
